// pages/ad/ad.js
//获取应用实例
const app = getApp()
let innerAudioContext = null //背景音乐
const animationObj = {
  curMoveArr: [],
  duration: 7500,
}
let winW = 0
let barArr = ['bar0', 'bar1', 'bar2', 'bar3', 'bar4', 'bar5', 'bar6', 'bar7', 'bar8']
// 滚动频道分组，避免前后重贴
let barGroup = [
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8]
]
let prevRunBarNum = ''
// 后端把数据整成该格式即可
let commentData = [
  {
    img: '../../images/portrait1.jpg',
    name: 'sop0',
    txt: '拼团成功！获得奖励256元'
  },
  {
    img: '../../images/portrait1.jpg',
    name: 'sop1',
    txt: '拼团成功！获得奖励53元'
  },
  {
    img: '../../images/portrait1.jpg',
    name: 'sop2',
    txt: '拼团成功！获得奖励53元'
  },
  {
    img: '../../images/portrait1.jpg',
    name: 'sop3',
    txt: '拼团成功！获得奖励53元'
  },
  {
    img: '../../images/portrait1.jpg',
    name: 'sop4',
    txt: '拼团成功！获得奖励53元'
  }
]
let commentCurIndex = 0
// animationObj.curMoveArr
Page({
  /**
   * 页面的初始数据
   */
  data: {
    bar0: '',
    bar1: '',
    bar2: '',
    bar3: '',
    bar4: '',
    bar5: '',
    bar6: '',
    bar7: '',
    bar8: '',
    bar0Content: {},
    bar1Content: {},
    bar2Content: {},
    bar3Content: {},
    bar4Content: {},
    bar5Content: {},
    bar6Content: {},
    bar7Content: {},
    bar8Content: {},
    curSelectTab: 0,
    commentTimer: null, // 评论播放定时器
    isPlayComment: true, // 是否播评论语    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    winW = wx.getSystemInfoSync().windowWidth // 屏幕宽度
    this.toggleMusic(1)
    this.playComment() // 初始化定时播放评论语
  },
  onHide: function() {
    // console.log('隐藏')
    this.toggleMusic(0)
    // 销毁评论部
    let timer = this.data.commentTimer
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    this.setData({
      commentTimer: timer
    })
  },
  /**
   * 定时器播放评论语
   */
  playComment() {
    let timer = this.data.commentTimer
    if (timer) {
      clearInterval(timer)
      timer = null
    }

    var nowDate = this.turnDate()
    var curDateStamp = nowDate.timeStamp / 1000 // 转成秒
    // debugger
    // console.log('播放评论语')
    timer = setInterval(() => {
      // debugger
      // console.log('播放评论语')
      const name = this.commentAnimationFn()
      this.listenBarArrLen(curDateStamp) // 监听bar剩余量
      this.ininAnimation(name, curDateStamp) // 评论语动画执行
      curDateStamp++
    }, 1000)
    // debugger
    this.setData({
      commentTimer: timer
    })
  },
  /**
   * 评论语动画
   */
  commentAnimationFn() {
    // debugger
    // ['bar1', 'bar2', 'bar3', 'bar4', 'bar5', 'bar6']
    let len = barArr.length
    
    if (len <= 0) {
      // console.log('1.资源告急，请稍等！')
      return
    }
    let num = Math.round(Math.random() * len)
    num = Math.max(num, 0)
    num = Math.min(num, len - 1)
    // console.log('barArr:', barArr, ', num:', num)
    let name = barArr[num]
    // 对比最近两次运行的bar，避免前后重叠
    // console.log(typeof prevRunBarNum)
    if (typeof prevRunBarNum === 'number') {
      // debugger
      let isStop = false
      let curBarNum = Number(name.substr(name.length - 1, 1))

      for (let itemArr of barGroup){
        if (itemArr.indexOf(curBarNum) > -1 && itemArr.indexOf(prevRunBarNum) > -1){
          // console.log('前后太近，避免重贴', prevRunBarNum, curBarNum)
          isStop = true
          return
        }
      }

      if (isStop){
        // debugger
        return
      }
    }
    barArr.splice(num, 1)
    if (name){
      // debugger
      prevRunBarNum = Number(name.substr(name.length - 1, 1))
    }
    
    // console.log(num,name,'barArr:', barArr)
    if (commentCurIndex >= commentData.length) {
      commentCurIndex = 0
    }
    let txt = commentData[commentCurIndex]
    let title = name + 'Content'
    // console.log(name, title, 'txt', txt, ',commentCurIndex"', commentCurIndex)
    commentCurIndex++
    this.setData({
      [title]: txt
    })
    return name

  },
  /**
   * 评论语动画执行
   */
  ininAnimation(name, curDateStamp) {
    if (!name)return
    const stamp = curDateStamp * 1000
    animationObj.curMoveArr.push({
      name: name,
      stamp: stamp
    })
    // 获取宽度
    let barW = 800
    let _self = this
    const query = wx.createSelectorQuery()
    query.select('#' + name).boundingClientRect(function(res) {
      // debugger
      //console.log(name, 'res', res)
      res = res || {
        width: 800
      }
      barW = res.width

      let left = (barW + winW) * -1
      // console.log(name, '开始运动left:', left)
      // 动画初始化
      let animationLeft = wx.createAnimation({
        duration: animationObj.duration,
        timingFunction: 'linear',
        delay: 0
      })
      animationLeft.height('auto').left(left).step()
      _self.setData({
        [name]: animationLeft.export()
      })

    })
    query.exec()

  },
  /**
   * 监听bar剩余量
   */
  listenBarArrLen(curDateStamp) {
    var stamp = curDateStamp * 1000
    animationObj.curMoveArr.forEach((obj, index) => {
      // debugger
      const disStamp = stamp - obj.stamp // 时间差 = 上一次开始时间 - 当前时间
      const maxStamp = animationObj.duration // 时间差 必须大于 运动所需时间才能放行
      const surplusStamp = disStamp - maxStamp
      // console.log('surplusStamp:', surplusStamp)
      // debugger
      // 已跑完一趟，为进入下一趟做准备
      if (surplusStamp > 0) {
        // console.log('可以运行了', obj)
        // debugger
        // 先隐藏，并将其移到最右边
        let animationLeft = wx.createAnimation({
          duration: 20,
          timingFunction: 'linear'
        })
        // debugger
        animationLeft.height(0).left(winW * 2).step()
        this.setData({
          [obj.name]: animationLeft.export()
        })
        barArr.push(obj.name)
        animationObj.curMoveArr.splice(index, 1)
      }
    })
  },
  /**
   * 切换评论语是否播放
   */
  toggleComment() {
    let curState = !this.data.isPlayComment
    this.setData({
      isPlayComment: curState
    })
    if (curState) {
      // this.commentAnimationFn() // 默认开启播放评论语
      this.playComment() // 初始化定时播放评论语
    } else {
      //debugger
      //console.log('暂停播放评论语')
      let timer = this.data.commentTimer
      if (timer) {
        clearInterval(timer)
        timer = null
        this.setData({
          commentTimer: timer
        })
      }

    }
  },
  /**
   * 暂停/播放 音乐
   * @params{Boolean} playing 1.true 2.false
   */
  toggleMusic: function(playing) {
    //debugger
    if (!innerAudioContext) {
      this.initMusic()
    }

    let isPlay = !this.data.isPlayMusic
    if (playing === 1) {
      isPlay = true
    } else if (playing === 0) {
      isPlay = false
    }
    this.setData({
      isPlayMusic: isPlay
    })
    if (isPlay) {
      // console.log('播放', innerAudioContext)
      this.playMusic()
    } else {
      // console.log('暂停', innerAudioContext)
      this.stopMusic()
    }
  },
  /**
   * 开始播放音乐
   */
  playMusic() {
    innerAudioContext.play()
  },
  /**
   * 暂停播放音乐
   */
  stopMusic() {
    innerAudioContext.pause()
  },
  /**
   * 初始化音乐播放器
   */
  initMusic() {
    innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true // 自动播放
    innerAudioContext.loop = true // 循环播放
    const src1 = 'http://audio01.dmhmusic.com/71_53_T10046221354_128_4_1_0_sdk-cpm/0207/M00/66/33/ChR47FsrnnaAaaArAEBKMzL4rQM751.mp3?xcode=74de35833fc0423d4e85c8d3849ec435f1610bb'
    const src = src1
    innerAudioContext.src = src
    innerAudioContext.onError((res) => {
      console.log('播放出错，', res)
    })
  },
  /*
    倒计时  分钟和秒倒计时
    思路：
    1.设置一个倒计时的时间长度；
    2.设置开始时间和当前时间；
    3.结束时间是 开始时间+倒计时间；
    4.结束毫秒-开始毫秒=剩余倒计时间。
    time 分钟整数
  */
  resetTime: function(featureDate) {
    // 计算时间差(disStamp) = 未来日期(featureDate) - 当前日期(nowDate)
    var featDate = this.turnDate(featureDate)
    var nowDate = this.turnDate()
    var disStamp = featDate.timeStamp - nowDate.timeStamp
    var curDateStamp = nowDate.timeStamp / 1000
    var surplusTimes = disStamp / 1000

    var _self = this
    surplusTimes--;
    curDateStamp++;
    _self.cutdownTimeFn(surplusTimes, curDateStamp)

    // 进入倒计时
    var countdowns = setInterval(function() {
      surplusTimes--;
      curDateStamp++;
      _self.cutdownTimeFn(surplusTimes, curDateStamp)
      if (surplusTimes <= 0) {
        clearInterval(countdowns);
      }
    }, 1000);
  },
  /**
   * 倒计时
   */
  cutdownTimeFn(surplusTimes, curDateStamp) {
    var days = this.dateFormatter(parseInt(surplusTimes / (60 * 60 * 24)));
    var hours = this.dateFormatter(parseInt((surplusTimes % (60 * 60 * 24)) / (60 * 60)));
    var minu = this.dateFormatter(parseInt((surplusTimes % (60 * 60)) / (60)));
    var secd = this.dateFormatter(parseInt(surplusTimes % 60));
    // console.log(days + '天' + hours+':'+ minu + ':' + secd);
    if (this.data.actionflag == '0') { //结束状态
      if (this.data.pageinfo.stoptime > curDateStamp) {
        this.data.actionflag = '1'
        this.setData({
          actionflag: this.data.actionflag
        })
      }
    } else { //活动进行中
      if (this.data.pageinfo.stoptime < curDateStamp) {
        this.data.actionflag = '0'
        this.setData({
          actionflag: this.data.actionflag
        })
      }
    }
    this.setData({
      curDateStamp: curDateStamp,
      cutdonTimer: {
        day: days,
        hour: hours,
        minu: minu,
        secd: secd,
        stamp: surplusTimes * 1000
      }
    })
  },
  /**
   * 单字符格式化
   * @param str
   * @returns {string}
   */
  dateFormatter: function(str) {
    if (!str) return '00'
    const s = str.toString()
    return s.length > 1 ? s : '0' + s
  },
  /** 
   * 时间转换
   * @param timeStamp
   * @returns Object
   */
  turnDate: function(timeStamp) {
    timeStamp = timeStamp || ''
    let date = ''
    if (!timeStamp) {
      date = new Date()
      timeStamp = date.getTime()
    } else {
      date = new Date(timeStamp)
      timeStamp = date.getTime()
    }
    const year = date.getFullYear()
    const month = this.dateFormatter((date.getMonth() + 1))
    const day = this.dateFormatter(date.getDate())
    const hours = this.dateFormatter(date.getHours())
    const minutes = this.dateFormatter(date.getMinutes())
    const seconds = this.dateFormatter(date.getSeconds())

    const obj = {
      year: year,
      month: month,
      day: day,
      hours: hours,
      minutes: minutes,
      seconds: seconds,
      timeStamp: timeStamp
    }
    return obj
  }

})